import 'package:flutter/material.dart';
import 'package:flutter_ble_demo/model/device_model.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:flutter_comm_base_framework/core/CommBasePage.dart';
import 'package:flutter_comm_base_framework/core/utils/ColorsUtil.dart';
import 'package:flutter_comm_base_framework/core/view/my_appbar.dart';
import 'package:flutter_comm_base_framework/core/widgets/custom_button.dart';
import 'package:flutter_comm_base_framework/core/widgets/custom_text.dart';
import 'package:permission_handler/permission_handler.dart';

class BluetoothBleTestPage extends CommBasePage{

  @override
  CommBaseState getPageState() {
    return BluetoothBleTestPageState();
  }
}

class BluetoothBleTestPageState extends CommBaseState<BluetoothBleTestPage>{

  List<BluetoothDevice> deviceLst = [];

  @override
  void initBaseParams() {

  }

  @override
  void initPageData() {
  }


  @override
  Widget getViewsWidget() {
    return Scaffold(
      appBar: MyAppBar(
        title: Text('Flutter BLE Demo',style: TextStyle(fontSize: 18,color: Colors.white),),
      ),
      body: Column(
        children: [
          Row(
            children: [
              Expanded(
                flex: 1,
                child: CustomButton("搜索蓝牙",toScanBLE,margin: EdgeInsets.all(10),),
              ),
              Expanded(
                flex: 1,
                child: CustomButton("停止搜索",toStopScanBLE,margin: EdgeInsets.all(10),),
              ),
            ],
          ),
          Expanded(
            flex: 1,
            child: ListView.builder(
                itemCount: deviceLst.length,
                itemBuilder: (BuildContext context, int index){
                  return getDeviceView(index);
                }
            ),
          ),
        ],
      ),
    );
  }

  Widget getDeviceView(int index){
    BluetoothDevice device = deviceLst[index];
    print('load:${device.name} found! id: ${device.id.id}');
    return GestureDetector(
      onTap: (){
        Navigator.of(context).pushNamed("/sendAndReceive",arguments: device);
      },
      child: Column(children: [
        CustomText(device.name,
          padding: EdgeInsets.all(15),
          bgColor: Colors.white,
          margin: EdgeInsets.only(bottom: 1),
        ),
        CustomText(device.id.id,
          padding: EdgeInsets.all(15),
          bgColor: Colors.white,
          margin: EdgeInsets.only(bottom: 1),
        )
      ],),
    );
  }

  Future<void> toScanBLE() async {
    if (!await Permission.locationWhenInUse.serviceStatus.isEnabled) {
      showToastTip("请开启位置服务");
      return;
    }

    if(!await Permission.location.request().isGranted) {
      return;
    }
    if(!await Permission.bluetooth.request().isGranted) {
      return;
    }

    FlutterBlue.instance.startScan(timeout: Duration(seconds: 30));
    FlutterBlue.instance.scanResults.listen((results) {
      for (ScanResult r in results) {
        bool hasDev = false;
        print('${r.device.name} found! rssi: ${r.rssi}  id: ${r.device.id.id} advertisementData:${r.advertisementData}');
        for(int i=0,count=deviceLst.length;i<count;i++){
          BluetoothDevice devicei = deviceLst[i];
          if(devicei.id.id == r.device.id.id){
            hasDev = true;
            break;
          }
        }
        if(!hasDev && r.device.name.length>0){
          setState(() {
            deviceLst.add(r.device);
          });
        }
      }
    });
  }

  void toStopScanBLE(){
    FlutterBlue.instance.stopScan();
  }

  @override
  void dispose() {
    super.dispose();
    toStopScanBLE();
  }
}